package com.baiyang.server.tools;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.baiyang.server.model.system.Tree;
import com.baiyang.server.model.system.User;

public class DataTool {
	public static final SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss");
	public static final SimpleDateFormat sdf_ymd = new SimpleDateFormat("yyyy-MM-dd");
	public static final SimpleDateFormat sdf_hms = new SimpleDateFormat("HH:mm:ss");
	/**
	 * @return
	 * 生成UUID
	 */
	public static String createUUID() {
		return UUID.randomUUID().toString().replaceAll("-", "");
	}
	/**
	 * 判断字符出是否为
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isBlank(String str) {
		if (str == null || "".equals(str)) {
			return true;
		} else {
			return false;
		}
	}
	
	public static boolean isBlank(List<?> t) {
		if(t ==null || t.size() == 0) {
			return true;
		}else {
			return false;
		}
			
	}
	
	public static String getUserIdFromSession(HttpServletRequest request) {
		HttpSession session = request.getSession();
		User user = (User) session.getAttribute(Data.Session.USER);
		String userId  = user==null?null:user.getId();
		return userId;
	}
	
	/**
	 * @apiNote 生产树结构
	 * @param tree 所有节点
	 * @param root 根节点
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Tree getTree(List<? extends Tree> tree, Tree root) {
		String id = root.getId();
		List<Tree> childens = root.getChildrens();
		if (childens == null) {
			childens = new ArrayList<Tree>();
			root.setChildrens(childens);
		}
		if (DataTool.isBlank(id)) {
			if(tree == null || tree.size() == 0) {
				return root;
			}
			tree.forEach(e -> {
				if (DataTool.isBlank(e.getParentId())) {
					root.setChildren(e);
				}
			});
		} else {
			tree.forEach(e -> {
				if (!DataTool.isBlank(e.getParentId())&&id.equals(e.getParentId())) {
					root.setChildren(e);
				}
			});
		}
		if (childens.size() != 0) {
			root.sorted();
			for (int i = 0; i < childens.size(); i++) {
				getTree(tree, childens.get(i));
			}
		}
		return root;
	}
}
